package com.shigu.wxpaysdk;

import com.shigu.wxpaysdk.common.Configure;
import com.shigu.wxpaysdk.common.HttpsRequest;
import com.shigu.wxpaysdk.common.Signature;
import com.shigu.wxpaysdk.request.PayRequest;

/**
 * Created by wxc on 2016/12/13.
 *
 * @author wxc
 * @version wxpaysdk 0.0.1
 * @since wxpaysdk 0.0.1
 */
public class WXPay {

    private static final String host = "https://api.mch.weixin.qq.com";

    public static void init(String appid, String mch_id, String key) {
        Configure.appid = appid;
        Configure.mch_id = mch_id;
        Configure.key = key;
    }

    /**
     * 单次调用测试服
     * @param request API
     * @param <T> 响应类型
     * @return 响应
     * @throws Exception
     */
    public static <T> T test(PayRequest<T> request) throws Exception {
        boolean flag = Configure.test;
        Configure.test = true;
        try {
            return run(request);
        } finally {
            if (!flag)
                Configure.test = false;
        }
    }
    public static <T> T run(PayRequest<T> request) throws Exception {
        Class<? extends PayRequest> clazz = request.getClass();
        String apiUrl = parseRequest(clazz.getSimpleName());
        if (Configure.test)
            apiUrl = "/sandboxnew" + apiUrl;

        Signature.sign(request);
        HttpsRequest post = new HttpsRequest();
        return post.sendPost(host + apiUrl, request);
    }

    private static String parseRequest(String str) {
        char[] ch = str.toCharArray();
        String apiName = "";
        int tmp = 0;
        for (int i = 1; i < ch.length; i++) {
            if ((int) ch[i] >= 65 && (int) ch[i] <= 90) {
                apiName += "/" + str.substring(tmp, i).toLowerCase();
                tmp = i;
            }
        }
        return apiName + "/" + str.substring(tmp).toLowerCase();
    }
}
